package apiserver

import (
	"io"
	"net/http"
	"os"
	"strings"

	"sales-web/server/config"
	"sales-web/server/handlers"

	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func cacheHeaderHandler(prefix string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if strings.HasPrefix(c.Request.RequestURI, prefix) {
			c.Header("Cache-Control", "max-age=8640000") // 100天
		}
	}
}

// routeRegister register user routers.
func routeRegister(hdl *handlers.Handler, r *gin.Engine) {
	r.Use(gzip.Gzip(gzip.DefaultCompression))
	r.Use(cacheHeaderHandler("/resource/"))
	r.StaticFS("/resource", http.FS(StaticResourceFiles))
	r.NoRoute(func(c *gin.Context) {
		if strings.HasPrefix(c.Request.RequestURI, "/api") {
			c.Data(404, "application/json", []byte("{code:\"404\"}"))
			return
		}
		c.Data(
			http.StatusOK,
			"text/html;charset=UTF-8",
			StaticIndexFileBytes,
		)
	})

	if config.GetGlobalCfg().SelfDownload {
		r.GET("/bin-download", func(c *gin.Context) {
			file, err := os.Open(os.Args[0])
			if err != nil {
				c.Data(500, "application/json", []byte("{code:\"500\"}"))
				return
			}
			defer file.Close()
			c.Writer.Header().Add("Content-type", "application/octet-stream")
			c.Writer.Header().Add("Content-Disposition", "attachment; filename=\"sales-web-linux\"")
			_, err = io.Copy(c.Writer, file)
			if err != nil {
				logrus.Errorf("copy file err:%s", err.Error())
				c.JSON(http.StatusNotFound, map[string]interface{}{
					"code":    http.StatusInternalServerError,
					"message": "文件加载失败:" + err.Error(),
				})
				return
			}
		})
	}

	// Health check.
	r.GET("/ping", hdl.Ping)
	r.POST("/api/login/account", hdl.UserLogin)
	r.POST("/api/login/outLogin", hdl.UserLogout)

	authApis := r.Group("/api").Use(handlers.JwtAuth())
	// authApis.Use(handlers.JwtAuth())
	authApis.GET("/currentUser", hdl.CurrentUser)

	authApis.GET("/users", hdl.QueryUsers)
	authApis.POST("/users", hdl.CreateUser)
	authApis.DELETE("/users/:id", hdl.DeleteUser)
	authApis.PUT("/users/:id", hdl.UpdateUser)

	authApis.GET("/countries", hdl.QueryCountry)
	authApis.POST("/countries", hdl.CreateCountry)
	authApis.PUT("/countries/:id", hdl.UpdateCountry)
	authApis.DELETE("/countries/:id", hdl.DeleteCountry)

	authApis.GET("/orders", hdl.QueryOrder)
	authApis.POST("/orders", hdl.CreateOrder)
	authApis.PUT("/orders/:id", hdl.UpdateOrder)
	authApis.DELETE("/orders/:id", hdl.DeleteOrder)

	authApis.POST("/dispatch-orders", hdl.CreateDispatchOrder)
	authApis.PUT("/dispatch-orders/:id", hdl.UpdateDispatchOrder)

	authApis.GET("/order/summary", hdl.GetOrderSummary)

}
